<template>
  <view class="word-learning-container">
    <view class="header">
      <h1>单词学习</h1></view>
      <view class="progress-bar">
        <view class="progress-text">
          {{ currentIndex + 1 }} / {{ words.length }}
        </view>
        <view class="progress">
          <view 
            class="progress-fill" 
            :style="{ width: ((currentIndex + 1) / words.length) * 100 + '%' }"
          ></view>
        </view>
      </view>
    </view>

    <view class="word-card" v-if="currentWord">
      <view class="word-pronunciation">
        <h2 class="word">{{ currentWord.word }}</h2>
        <button 
          class="play-button" 
          @click="playPronunciation"
          :disabled="isPlaying"
        >
          <i :class="isPlaying ? 'fa fa-spinner fa-spin' : 'fa fa-volume-up'">
            {{ isPlaying ? '播放中...' : '播放发音' }}
          </i>
        </button>
      </view>

      <view class="word-details">
        <view class="phonetic">
          <span class="label">音标：</span>
          <span class="value">{{ currentWord.phonetic || '暂无音标' }}</span>
        </view>
        
        <view class="part-of-speech" v-for="(definition, index) in currentWord.definitions" :key="index">
          <span class="pos">{{ definition.partOfSpeech }}</span>
          <ul class="definition-list">
            <li v-for="(def, i) in definition.definition" :key="i">{{ def }}</li>
          </ul>
        </view>

        <view class="examples" v-if="currentWord.examples && currentWord.examples.length > 0">
          <span class="label">例句：</span>
          <view v-for="(example, index) in currentWord.examples" :key="index" class="example">
            <p class="example-text">{{ example.text }}</p>
            <p class="example-translation">{{ example.translation }}</p>
          </view>
        </view>
      </view>

      <view class="learning-actions">
        <button class="btn btn-easy" @click="markEasy">认识</button>
        <button class="btn btn-medium" @click="markMedium">模糊</button>
        <button class="btn btn-hard" @click="markHard">不认识</button>
      </view>

      <view class="card-actions">
        <button v-if="currentIndex > 0" class="btn btn-secondary" @click="prevWord">上一个</button>
        <button class="btn btn-primary" @click="nextWord">下一个</button>
      </view>
    </view>

    <view class="learning-finished" v-else-if="words.length > 0 && currentIndex >= words.length">
      <h2>恭喜！您已完成当前学习任务</h2>
      <p>今日学习单词数：{{ words.length }}</p>
      <p>掌握程度统计：</p>
      <view class="stats-container">
        <view class="stat-item">
          <span class="stat-label">认识：</span>
          <span class="stat-value easy">{{ easyCount }}</span>
        </view>
        <view class="stat-item">
          <span class="stat-label">模糊：</span>
          <span class="stat-value medium">{{ mediumCount }}</span>
        </view>
        <view class="stat-item">
          <span class="stat-label">不认识：</span>
          <span class="stat-value hard">{{ hardCount }}</span>
        </view>
      </view>
      <button class="btn btn-primary" @click="restartLearning">重新学习</button>
      <button class="btn btn-secondary" @click="goBack">返回</button></view>
<!-- 此 </view> 标签为多余，已移除 -->


    <view class="no-words" v-else>
      <h2>暂无学习单词</h2>
      <p>请先创建单词集或选择学习计划</p>
      <button class="btn btn-primary" @click="goToWordSet">前往单词集</button>
    </view>
</template>
<!-- 移除多余的 </view> 标签 -->
<!-- 移除多余的 </view> 标签后，此处为修复模板结束标签 -->
<script>
import { ref, computed, onMounted } from 'vue'
import { useUserStore, useConfigStore } from '../../store'

export default {
  name: 'WordLearning',
  setup() {
    // 使用uni.getLaunchOptionsSync获取路由参数
    const options = uni.getLaunchOptionsSync()
    const routeParams = options.query || {}
    
    const userStore = useUserStore()
    const configStore = useConfigStore()
    
    // 状态管理
    const words = ref([])
    const currentIndex = ref(0)
    const isPlaying = ref(false)
    const wordStatus = ref({})
    const learningStartTime = ref(Date.now())
    
    // 计算属性
    const currentWord = computed(() => {
      return words.value[currentIndex.value] || null
    })
    
    const easyCount = computed(() => {
      return Object.values(wordStatus.value).filter(status => status === 'easy').length
    })
    
    const mediumCount = computed(() => {
      return Object.values(wordStatus.value).filter(status => status === 'medium').length
    })
    
    const hardCount = computed(() => {
      return Object.values(wordStatus.value).filter(status => status === 'hard').length
    })
    
    // 初始化学习数据
    const initializeLearning = async () => {
      try {
        const wordSetId = routeParams.wordSetId
        const planId = routeParams.planId
        
        // 模拟数据 - 实际项目中应从API获取
        if (!words.value.length) {
          words.value = generateMockWords()
        }
        
        // 如果是从学习计划进入，记录开始时间
        if (planId) {
          learningStartTime.value = Date.now()
        }
      } catch (error) {
        console.error('初始化学习数据失败', error)
      }
    }
    
    // 生成模拟单词数据
    const generateMockWords = () => {
      return [
        {
          id: 1,
          word: 'aberration',
          phonetic: '/ˌæbəˈreɪʃn/',
          definitions: [
            {
              partOfSpeech: 'n.',
              definition: ['偏差，偏离', '脱离常轨的行为或现象']
            }
          ],
          examples: [
            {
              text: 'The decision to close the hospital was an aberration in the government\'s health policy.',
              translation: '关闭医院的决定是政府卫生政策中的一个偏差。'
            }
          ]
        },
        {
          id: 2,
          word: 'abjure',
          phonetic: '/əbˈdʒʊə(r)/',
          definitions: [
            {
              partOfSpeech: 'v.',
              definition: ['发誓放弃，宣誓弃绝', '宣布放弃（信仰、主张等）']
            }
          ],
          examples: [
            {
              text: 'He abjured his allegiance to the former regime.',
              translation: '他宣誓放弃对前政权的效忠。'
            }
          ]
        },
        {
          id: 3,
          word: 'ablution',
          phonetic: '/əˈbluːʃn/',
          definitions: [
            {
              partOfSpeech: 'n.',
              definition: ['沐浴，净身', '（宗教仪式中的）净手礼']
            }
          ],
          examples: [
            {
              text: 'The priest performed the ablution before beginning the ceremony.',
              translation: '牧师在开始仪式前进行了净手礼。'
            }
          ]
        },
        {
          id: 4,
          word: 'abnegation',
          phonetic: '/ˌæbnɪˈɡeɪʃn/',
          definitions: [
            {
              partOfSpeech: 'n.',
              definition: ['放弃，克制', '自我牺牲']
            }
          ],
          examples: [
            {
              text: 'Her abnegation of personal comfort for the sake of others was admirable.',
              translation: '她为了他人而放弃个人舒适的精神令人钦佩。'
            }
          ]
        },
        {
          id: 5,
          word: 'abominate',
          phonetic: '/əˈbɒmɪneɪt/',
          definitions: [
            {
              partOfSpeech: 'v.',
              definition: ['痛恨，憎恶', '极度厌恶']
            }
          ],
          examples: [
            {
              text: 'I abominate discrimination in all its forms.',
              translation: '我痛恨一切形式的歧视。'
            }
          ]
        }
      ]
    }
    
    // 播放单词发音
    const playPronunciation = async () => {
      if (!currentWord.value) return
      
      try {
        isPlaying.value = true
        const voiceSettings = configStore.voiceSettings
        
        // 在uni-app中使用createInnerAudioContext
        const audioContext = uni.createInnerAudioContext()
        
        // 设置音频源 - 这里使用模拟的音频URL
        // 实际项目中应该从API获取
        const mockAudioUrl = `https://api.dictionaryapi.dev/media/pronunciations/en/${currentWord.value.word}-us.mp3`
        audioContext.src = mockAudioUrl
        
        audioContext.onPlay(() => {
          console.log('开始播放')
        })
        
        audioContext.onError((err) => {
          console.error('播放失败', err)
          isPlaying.value = false
          // 模拟播放完成
          setTimeout(() => {
            isPlaying.value = false
          }, 1000)
        })
        
        audioContext.onEnded(() => {
          console.log('播放结束')
          isPlaying.value = false
        })
        
        await audioContext.play()
        
        // 保存音频上下文引用，以便后续可以停止播放
        audioContextRef.value = audioContext
        
      } catch (error) {
        console.error('播放发音失败', error)
        isPlaying.value = false
      }
    }
    
    // 标记单词掌握程度
    const markWordStatus = (status) => {
      if (!currentWord.value) return
      
      wordStatus.value[currentWord.value.id] = status
      
      // 如果开启了自动播放，先播放发音
      if (configStore.appSettings.autoPlayPronunciation && !isPlaying.value) {
        setTimeout(() => {
          nextWord()
        }, 500)
      } else {
        nextWord()
      }
    }
    
    // 标记为认识
    const markEasy = () => {
      markWordStatus('easy')
    }
    
    // 标记为模糊
    const markMedium = () => {
      markWordStatus('medium')
    }
    
    // 标记为不认识
    const markHard = () => {
      markWordStatus('hard')
    }
    
    // 下一个单词
    const nextWord = () => {
      if (currentIndex.value < words.value.length - 1) {
        currentIndex.value++
        // 如果开启了自动播放，自动播放下一个单词的发音
        if (configStore.appSettings.autoPlayPronunciation) {
          setTimeout(playPronunciation, 300)
        }
      } else if (currentIndex.value === words.value.length - 1) {
        currentIndex.value++
        // 完成学习，记录学习时间
        const studyTime = Math.floor((Date.now() - learningStartTime.value) / 1000 / 60)
        saveLearningProgress(studyTime)
      }
    }
    
    // 上一个单词
    const prevWord = () => {
      if (currentIndex.value > 0) {
        currentIndex.value--
        // 如果开启了自动播放，自动播放当前单词的发音
        if (configStore.appSettings.autoPlayPronunciation) {
          setTimeout(playPronunciation, 300)
        }
      }
    }
    
    // 保存学习进度
    const saveLearningProgress = (studyTime) => {
      try {
        // 这里应该调用API保存学习进度
        console.log('保存学习进度', {
          studyTime,
          wordsLearned: words.value.length,
          wordStatus: wordStatus.value
        })
        
        // 更新本地store中的进度
        // progressStore.updateDailyProgress({...})
      } catch (error) {
        console.error('保存学习进度失败', error)
      }
    }
    
    // 重新学习
    const restartLearning = () => {
      currentIndex.value = 0
      wordStatus.value = {}
      learningStartTime.value = Date.now()
    }
    
    // 保存音频上下文引用
    const audioContextRef = ref(null)
    
    // 返回上一页
    const goBack = () => {
      uni.navigateBack()
    }
    
    // 前往单词集页面
    const goToWordSet = () => {
      uni.navigateTo({
        url: '/pages/wordset/WordSet'
      })
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeLearning()
      
      // 如果开启了自动播放，自动播放第一个单词的发音
      if (configStore.appSettings.autoPlayPronunciation) {
        setTimeout(playPronunciation, 500)
      }
    })
    
    return {
      words,
      currentIndex,
      currentWord,
      isPlaying,
      easyCount,
      mediumCount,
      hardCount,
      playPronunciation,
      markEasy,
      markMedium,
      markHard,
      nextWord,
      prevWord,
      restartLearning,
      goBack,
      goToWordSet,
      audioContextRef
    }
  }
}
</script>

<style scoped>
.word-learning-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #333;
  margin-bottom: 15px;
}

.progress-bar {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.progress {
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

.word-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 30px;
}

.word-pronunciation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.word {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.play-button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: background-color 0.3s ease;
}

.play-button:hover:not(:disabled) {
  background-color: #2980b9;
}

.play-button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.word-details {
  margin-bottom: 25px;
}

.phonetic {
  margin-bottom: 15px;
  font-style: italic;
  color: #666;
}

.label {
  font-weight: 500;
}

.part-of-speech {
  margin-bottom: 15px;
}

.pos {
  display: inline-block;
  background-color: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 8px;
}

.definition-list {
  margin: 0;
  padding-left: 20px;
}

.definition-list li {
  margin-bottom: 5px;
  line-height: 1.5;
}

.examples {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.example {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.example-text {
  margin: 0 0 5px 0;
  font-style: italic;
}

.example-translation {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.learning-actions {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  justify-content: center;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-easy {
  background-color: #4CAF50;
  color: white;
  flex: 1;
}

.btn-easy:hover {
  background-color: #45a049;
}

.btn-medium {
  background-color: #ff9800;
  color: white;
  flex: 1;
}

.btn-medium:hover {
  background-color: #e68900;
}

.btn-hard {
  background-color: #f44336;
  color: white;
  flex: 1;
}

.btn-hard:hover {
  background-color: #da190b;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background-color: #7f8c8d;
}

.card-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.learning-finished,
.no-words {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.learning-finished h2,
.no-words h2 {
  color: #333;
  margin-bottom: 20px;
}

.stats-container {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin: 20px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
}

.stat-value.easy {
  color: #4CAF50;
}

.stat-value.medium {
  color: #ff9800;
}

.stat-value.hard {
  color: #f44336;
}
</style>